package com.budwk.app.sqfw.services.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.dto.RallyExcelDTO;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.models.Sqfw_rally;
import com.budwk.app.sqfw.models.Sqfw_rally_sign;
import com.budwk.app.sqfw.services.SqfwRallyForAdminService;
import com.budwk.app.sqfw.services.SqfwRallyService;
import com.budwk.app.sqfw.services.SqfwRallySignForAdminService;
import com.budwk.app.sqfw.services.SqfwServicerecordService;
import com.budwk.app.sqfw.vo.SqfwRallyVO;
import com.budwk.app.sqfwV2.dto.TemplateFileDTO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: wk-mini-dev-env
 * @description: 社区活动服务实现
 * @author: LJT
 * @create: 2023-11-14 10:06
 **/
@IocBean(args = {"refer:dao"})
@Slf4j
public class SqfwRallyForAdminServiceImpl extends BaseServiceImpl<Sqfw_rally> implements SqfwRallyForAdminService {
    public SqfwRallyForAdminServiceImpl(Dao dao) {
        super(dao);
    }

    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd");// 统计时间格式
    private static final SimpleDateFormat START_FORMAT = new SimpleDateFormat("yyyy-MM-dd 00:00:00");// 开始统计时间格式
    private static final SimpleDateFormat END_FORMAT = new SimpleDateFormat("yyyy-MM-dd 23:59:59");// 结束统计时间格式

    @Inject
    private SqfwRallySignForAdminService sqfwRallySignForAdminService;

    @Inject
    private SqfwServicerecordService sqfwServicerecordService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SqfwRallyService sqfwRallyService;

    /**
     * 获取巡查记录的查询条件 Cnd类型
     *
     * @param bean
     */
    public Cnd buildConditionForQueryToCnd(SqfwRallyVO bean) {
        log.info("SqfwRallyForAdminServiceImpl buildConditionForQueryToCnd,Sqfw_rally:{}", JSONObject.toJSON(bean).toString());
        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (!"直属".equals(sysUser.getProvince())) {
            bean.setProvince(sysUser.getProvince());
        }
        if (!"直属".equals(sysUser.getCity())) {
            bean.setCity(sysUser.getCity());
        }
        if (!"直属".equals(sysUser.getDistrict())) {
            bean.setDistrict(sysUser.getDistrict());
        }
        if (!"直属".equals(sysUser.getCounty())) {
            bean.setCounty(sysUser.getCounty());
        }
        if (!"直属".equals(sysUser.getCommunity())) {
            bean.setCommunity(sysUser.getCommunity());
        }
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            cnd.orderBy(bean.getPageOrderName(), PageUtil.getOrder(bean.getPageOrderBy()));
        } else {
            cnd.orderBy("create_time", "desc");
        }
        if (Strings.isNotBlank(bean.getQueryAll())) {
            if ("观山湖区".equals(bean.getDistrict())) {
                SqlExpressionGroup rallyName = Cnd.exps("rally_name", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup rallyReleaseUserName = Cnd.exps("rally_release_user_name", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup rallyType = Cnd.exps("rally_type", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup community = Cnd.exps("community", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup activityType = Cnd.exps("rally_content_json->>'activityType'", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup typeOfService = Cnd.exps("rally_content_json->>'typeOfService'", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup focusOrNot = Cnd.exps("rally_content_json->>'focusOrNot'", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup volunteerOrNot = Cnd.exps("rally_content_json->>'volunteerOrNot'", "like", "%" + bean.getQueryAll() + "%");
                cnd.and(rallyName.or(rallyReleaseUserName).or(rallyType).or(community).or(activityType).or(typeOfService).or(focusOrNot).or(volunteerOrNot));
            } else {
                SqlExpressionGroup e1 = Cnd.exps("rally_name", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup e2 = Cnd.exps("rally_release_user_name", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup e3 = Cnd.exps("rally_type", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup e4 = Cnd.exps("district", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup e5 = Cnd.exps("county", "like", "%" + bean.getQueryAll() + "%");
                SqlExpressionGroup e6 = Cnd.exps("community", "like", "%" + bean.getQueryAll() + "%");
                cnd.and(e1.or(e2).or(e3).or(e4).or(e5).or(e6));
            }
        }
        // 活动标题
        if (StringUtils.isNotEmpty(bean.getRallyName())) {
            cnd.and("rally_name", "like", "%" + bean.getRallyName() + "%");
        }
        // 发布人
        if (StringUtils.isNotEmpty(bean.getRallyReleaseUserName())) {
            cnd.and("rally_release_user_name", "like", "%" + bean.getRallyReleaseUserName() + "%");
        }
        // 启用类型（0-否， 1-是）
        if (ObjectUtil.isNotEmpty(bean.getRallyType()) && !"观山湖区".equals(bean.getDistrict())) {
            cnd.and("rally_type", "=", String.valueOf(bean.getRallyType()));
        }
        if (StringUtils.isNotEmpty(bean.getProvince())) {
            cnd.and("province", "like", "%" + bean.getProvince() + "%");
        }
        if (StringUtils.isNotEmpty(bean.getCity())) {
            cnd.and("city", "like", "%" + bean.getCity() + "%");
        }
        // 发布区县
        if (StringUtils.isNotEmpty(bean.getDistrict())) {
            cnd.and("district", "like", "%" + bean.getDistrict() + "%");
        }
        // 发布街道
        if (StringUtils.isNotEmpty(bean.getCounty())) {
            cnd.and("county", "like", "%" + bean.getCounty() + "%");
        }
        // 社区、辖区
        if (StringUtils.isNotEmpty(bean.getCommunity())) {
            cnd.and("community", "like", "%" + bean.getCommunity() + "%");
        }
        // 时间
        if (StringUtils.isNotEmpty(bean.getQueryTime())) {
            String time[] = bean.getQueryTime().split(",");
            cnd.and("create_time", "between", new Object[]{START_FORMAT.format(new Date(Long.valueOf(time[0]))), END_FORMAT.format(new Date(Long.valueOf(time[1])))});
        }
        //-------------------------------世纪城街道新增条件-----------------------------------------
        // 新时代文明实践站
        if ("观山湖区".equals(bean.getDistrict())) {
            if (ObjectUtil.isNotEmpty(bean.getEventRegistrationTime())) {
                cnd.and(Sqfw_rally::getEventRegistrationTime, "=", bean.getEventRegistrationTime());
            }
            // 新时代文明实践站
            if (StringUtils.isNotBlank(bean.getActivityType())) {
                cnd.and(" rally_content_json->>'activityType'", "=", bean.getActivityType());
            }
            // 综合性文化服务中心
            if (StringUtils.isNotBlank(bean.getTypeOfService())) {
                cnd.and(" rally_content_json->>'typeOfService'", "=", bean.getTypeOfService());
            }
            // 是否重点活动
            if (ObjectUtil.isNotEmpty(bean.getFocusOrNot())) {
                cnd.and("rally_content_json->>'focusOrNot'", "=", bean.getFocusOrNot());
            }
            // 是否自愿服务
            if (ObjectUtil.isNotEmpty(bean.getVolunteerOrNot())) {
                cnd.and("rally_content_json->>'volunteerOrNot'", "=", bean.getVolunteerOrNot());
            }
            // 是否报名
            if (ObjectUtil.isNotEmpty(bean.getRallyType())) {
                if (1 == bean.getRallyType()) {
                    cnd.and("rally_type", "=", "2");
                } else {
                    cnd.and("rally_type", "!=", "2");
                }
            }
        }
        return cnd;
    }

    /**
     * 获取查询条件 String类型
     *
     * @param bean
     * @return
     */
    private String buildConditionForQueryToString(SqfwRallyVO bean, String queryAll, String queryTime) {
        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (!"直属".equals(sysUser.getProvince())) {
            bean.setProvince(sysUser.getProvince());
        }
        if (!"直属".equals(sysUser.getCity())) {
            bean.setCity(sysUser.getCity());
        }
        if (!"直属".equals(sysUser.getDistrict())) {
            bean.setDistrict(sysUser.getDistrict());
        }
        if (!"直属".equals(sysUser.getCounty())) {
            bean.setCounty(sysUser.getCounty());
        }
        if (!"直属".equals(sysUser.getCommunity())) {
            bean.setCommunity(sysUser.getCommunity());
        }
        StringBuffer sb = new StringBuffer(" select * from public.\"sqfw_rally\" where 1 = 1 ");
        if (Strings.isNotBlank(queryAll)) {
            sb.append(" and ( rally_name like '%").append(queryAll).append("%'")
                    .append(" OR rally_release_user_name like '%").append(queryAll).append("%'")
                    .append(" OR create_time like '%").append(queryAll).append("%'")
                    .append(" OR rally_type like '%").append(queryAll).append("%'")
                    .append(" OR district like '%").append(queryAll).append("%'")
                    .append(" OR county like '%").append(queryAll).append("%'")
                    .append(" OR community like '%").append(queryAll).append("%'");
        }
        if (Strings.isNotBlank(bean.getRallyName())) {
            sb.append(" and rally_name like '%").append(bean.getRallyName()).append("%'");
        }
        if (Strings.isNotBlank(bean.getRallyReleaseUserName())) {
            sb.append(" and rally_release_user_name like '%").append(bean.getRallyReleaseUserName()).append("%'");
        }
        if (!"null".equals(String.valueOf(bean.getRallyType()))) {
            sb.append(" and rally_type like '%").append(bean.getRallyType()).append("%'");
        }
        if (Strings.isNotBlank(bean.getProvince())) {
            sb.append(" and province like '%").append(bean.getProvince()).append("%'");
        }
        if (Strings.isNotBlank(bean.getCity())) {
            sb.append(" and city like '%").append(bean.getCity()).append("%'");
        }
        if (Strings.isNotBlank(bean.getDistrict())) {
            sb.append(" and district like '%").append(bean.getDistrict()).append("%'");
        }
        if (Strings.isNotBlank(bean.getCounty())) {
            sb.append(" and county like '%").append(bean.getCounty()).append("%'");
        }
        if (Strings.isNotBlank(bean.getCommunity())) {
            sb.append(" and community like '%").append(bean.getCommunity()).append("%'");
        }
        if (Strings.isNotBlank(queryTime)) {
            String time[] = queryTime.split(",");
            Date date1 = new Date();
            date1.setTime(Long.parseLong(time[0]));
            Date date2 = new Date();
            date2.setTime(Long.parseLong(time[1]));
            SimpleDateFormat SDF_START = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sb.append(" and create_time > '").append(SDF_START.format(date1)).append("' and create_time < '").append(SDF_START.format(date2)).append("'");
        }
        return sb.toString();
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public void deleteRally(String id) {
        Sqfw_rally sqfwRally = fetch(id);
        if (null == sqfwRally) {
            return;
        }
        // 删除活动表
        delete(id);
        Cnd cnd = Cnd.NEW();
        cnd.and("rally_id", "=", sqfwRally.getId());
        List<Sqfw_rally_sign> sqfwRallySigns = sqfwRallySignForAdminService.query(cnd);
        if (sqfwRallySigns.size() > 0) {
            List<String> ids = sqfwRallySigns.stream().map(Sqfw_rally_sign::getId).collect(Collectors.toList());
            // 删除报名表
            sqfwRallySignForAdminService.delete(ids);
        }
        // 删除任务记录
        Cnd cnd1 = Cnd.NEW();
        cnd1.and("rally_id", "=", id);
        sqfwServicerecordService.clear(cnd1);
    }

    @Override
    public TemplateFileDTO downloadFile(SqfwRallyVO bean, List<String> ids) {
        if (ObjectUtil.isEmpty(bean.getCode())) {
            throw new AppException("文件类型不能为空！");
        }
        TemplateFileDTO templateFileDTO = new TemplateFileDTO();
        List<String> idList = ids;
        // 如果ids为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(idList) || idList.size() <= 0) {
            Cnd cnd = buildConditionForQueryToCnd(bean);
            List<Sqfw_rally> rallyList = sqfwRallyService.query(cnd);
            if (rallyList.size() > 0) {
                idList = rallyList.stream().map(Sqfw_rally::getId).collect(Collectors.toList());
            } else {
                return templateFileDTO;
            }
        }
        // 时间
        String startTime = "";
        String endTime = END_FORMAT.format(new Date());
        if (StringUtils.isNotEmpty(bean.getQueryTime())) {
            String[] time = bean.getQueryTime().split(",");
            startTime = TIME_FORMAT.format(new Date(Long.parseLong(time[0])));
            endTime = TIME_FORMAT.format(new Date(Long.parseLong(time[1])));
        }
        if (9 == bean.getCode()) {
            RallyExcelDTO rallyExcelDTO = sqfwRallyService.generateRallyExcel(ids.get(0));
            templateFileDTO.setFileUrl(rallyExcelDTO.getExcelUrl());
            templateFileDTO.setFileNname(DownLoadFileNameEnum.ACTIVITY_PERSON_INFO.getName());
        } else {
            templateFileDTO = sqfwRallyService.generateByCode(bean.getCode(), startTime, endTime, idList);
        }
        return templateFileDTO;
    }

    /**
     * 检查是否有数据下载
     *
     * @param bean
     * @param ids
     * @return
     */
    @Override
    public List<TemplateFileDTO> checkDowloadData(SqfwRallyVO bean, List<String> ids) {
        List<String> idList = ids;
        // 如果ids为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(idList) || idList.size() <= 0) {
            Cnd cnd = buildConditionForQueryToCnd(bean);
            List<Sqfw_rally> rallyList = sqfwRallyService.query(cnd);
            if (rallyList.size() > 0) {
                idList = rallyList.stream().map(Sqfw_rally::getId).collect(Collectors.toList());
            } else {
                return new ArrayList<TemplateFileDTO>();
            }
        }
        List<TemplateFileDTO> templateFileDTOList = sqfwRallyService.changeTemplate(idList);
        TemplateFileDTO templateFileDTO = new TemplateFileDTO();
        templateFileDTO.setTemplageUrl(NutzIocUtils.getOssPrefix() + "/blankStencil/rally/【活动人员报名信息表】台账.xlsx");
        templateFileDTO.setCode(9);
        templateFileDTO.setFileNname(DownLoadFileNameEnum.ACTIVITY_PERSON_INFO.getName());
        templateFileDTO.setDataLabel("暂无数据");
        if (1 == idList.size()) {
            templateFileDTO.setDataLabel("全部数据");
        }
        templateFileDTOList.add(templateFileDTO);
        return templateFileDTOList;
    }
}
